package com.aiti.lulian.service.newCard;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.lulian.dto.newCard.EnterpriseCardQRParamDto;
import com.aiti.lulian.entity.newCard.CardQr;
import com.aiti.lulian.mapper.newCard.CardQrMapper;
import com.aiti.lulian.utils.BusinessUtil;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

/**
 * description:
 * auth fcb
 * date 2025-09-15 17:11
 **/
@Service
@Slf4j
public class CardQrService extends BaseSerivceImpl<CardQrMapper, CardQr> {

    /**
     * 生成名片的访问二维码.
     * 只按前端传的baseUrl创建二维码。参数都在baseUrl上
     * @param paramDto
     * @return
     */
    public String getCardQRByCardId(EnterpriseCardQRParamDto paramDto) {
        CardQr cardQr = this.baseMapper.queryByCardId(paramDto.getCardId());
        if(cardQr != null) {
            return cardQr.getCardCode();
        }
        String qrCode = this.generateQRCode(paramDto);
        CardQr newCardQr = new CardQr();
        newCardQr.setBaseId(IdUtil.simpleUUID());
        newCardQr.setCardId(paramDto.getCardId());
        newCardQr.setCardCode(qrCode);
        this.baseMapper.insert(newCardQr);
        return qrCode;
    }

    public CardQr queryByCardId(String cardId) {
        return this.baseMapper.queryByCardId(cardId);
    }

    private String generateQRCode(EnterpriseCardQRParamDto paramDto) {
        String baseUrl = paramDto.getBaseUrl();
        QrConfig qrConfig = new QrConfig();
        qrConfig.setHeight(paramDto.getHeight());
        qrConfig.setWidth(paramDto.getWidth());
        qrConfig.setErrorCorrection(ErrorCorrectionLevel.H);
        BufferedImage bufferedImage = QrCodeUtil.generate(baseUrl, qrConfig);
        return BusinessUtil.bufferedImageToBase64(bufferedImage, "png");
    }
}
